package datastruct.heap;

import datastruct.lineList.Array;

/**
 * @author RunningShrimp
 * @date 2021/5/24  18:09
 * @see <a href=""></a>
 */
public class MaxHeap<E extends Comparable<E>> {
    private Array<E> date;

    public MaxHeap(int capacity) {
        date = new Array<E>(capacity);
    }

    public MaxHeap() {
        date = new Array<E>();
    }

    public MaxHeap(E[] array) {
        date = new Array<E>(array);
        for (int i = parent(array.length - 1); i > 0; i--) {
            siftDown(i);
        }
    }

    public int size() {
        return date.size();
    }

    public boolean isEmpty() {
        return date.isEmpty();
    }


    boolean contains(E e) {
        return date.contains(e);
    }

    private int parent(int index) {
        if (index == 0) {
            throw new IllegalArgumentException("index-0 doesn't have parent");
        }
        return (index - 1) / 2;
    }

    private int leftChild(int index) {
        return index * 2 + 1;
    }

    private int rightChild(int index) {
        return index * 2 + 2;
    }

    public void add(E e) {
        date.addLast(e);
        siftUp(date.size() - 1);
    }

    private void siftUp(int k) {
        while (k > 0 && date.get(parent(k)).compareTo(date.get(k)) < 0) {
            date.swap(k, parent(k));
            k = parent(k);
        }
    }

    public E findMax() {
        if (date.size() == 0) {
            throw new IllegalArgumentException("Can not findMax when head is empty");
        }
        return date.get(0);
    }

    public E extractMax() {
        E ret = findMax();
        date.swap(0, date.size() - 1);
        date.removeLast();
        siftDown(0);
        return ret;
    }

    private void siftDown(int key) {
        while (leftChild(key) < date.size()) {
            int j = leftChild(key);
            if (j + 1 < date.size() && date.get(j + 1).compareTo(date.get(j)) > 0) {
                j = rightChild(key);
            }
            if (date.get(key).compareTo(date.get(j)) >= 0) {
                break;
            }
            date.swap(key, j);
            key = j;
        }
    }

    public E replace(E e) {
        E ret = findMax();
        date.set(e, 0);
        siftDown(0);
        return e;
    }

}
